#!/bin/bash
# version: V1.0.0 -- 202111221730
longtime=$(date +%Y%m%d%H%M)
#exec >> (tee -a ${PWD}/log/install-mysql.log)

if [ ! -f init_variable ]; then
    echo "[file:init_variable] is not found"
    exit
fi
if [ ! -f my.cnf.tpl ]; then
    echo "[file:my.cnf.tpl] is not found"
    exit
fi

statusServer() {
    SER_PID=$(ps -ef | grep "mysqld" | grep -v grep | awk -F" " '{print $2}')
    SER_COUNT=$(ps -ef | grep "mysqld" | grep -v grep | awk -F" " '{print $8}' | grep mysqld | grep -v grep | wc -l)
}


function generateConfig() {
    echo "[${longtime}] start install mysql"
    # 检查创建临时文件夹
    mkdir -p {tmp,bak}
    ## 读取初始化变量
    source init_variable
    # 检查变量,写入默认值
    source check_var
    checkAndSetVar
    # 替换模板,写入到临时配置文件
    printf "$(cat init_variable)\ncat << EOF\n$(cat my.cnf.tpl)\nEOF"|bash > tmp/my.cnf.tmp
}

##############安装部署##################
function deploy() {
    ########清除旧目录, 创建新目录########
    # 清除 mysql 目录
    if [ -d ${basedir} ]; then
        echo "[${longtime}] find the dir ${basedir} and remove... "
        rm -rf ${basedir}
    fi
    # 创建安装目录的上级目录
    mkdir -p $(dirname ${basedir})
    # 解压
    echo "packetName:${packetName},packet:${packet}"
    if [ ! -z "${packetName}" ]; then
        PacketFileName=$(pwd)/../${packetName}
        echo "PacketFileName:${PacketFileName}"
        tar -xvf ${PacketFileName}
        if [ $? -ne 0 ]; then
            echo -e "\033[31m Extract mysql fail tar -xvf ${PacketFileName}: \033[0m"
            tar -zxvf ${PacketFileName}
            if [ $? -ne 0 ]; then
                echo -e "\033[31m Extract mysql fail for tar -zxvf ${PacketFileName} and exit: \033[0m"
                exit 1
            fi
        fi
    fi
    PacketPath=$(pwd)/${packet}
    if [ ! -d ${PacketPath} ]; then
        echo "packet is not found :-- ${PacketPath} "
        exit 0
    fi
    # 移动并改名目录
    mv ${PacketPath} ${basedir}
    # 创建目录，拷贝相关脚本
    mkdir -p ${basedir}/sh
    # 拷贝脚本到运行目录
    cp mysql_reset.sh ${basedir}/sh
    cp mysql_clean_sock.sh ${basedir}/sh
    chmod +x ${basedir}/sh/*
    #######复制配置文件##########
    if [ "$(whoami)" == "root" ]; then
        # 备份文件
        if [ -f /etc/my.cnf ]; then
             mv /etc/my.cnf bak/my_${longtime}.cnf
        fi
        if [ -d /etc/mysql ]; then
            mv /etc/mysql bak/mysql_bak_${longtime}
        fi
        # 拷贝新配置文件
        cp tmp/my.cnf.tmp /etc/my.cnf
    else
        # 拷贝新配置文件
        cp tmp/my.cnf.tmp ${basedir}/my.cnf
    fi
    # 创建连接
    rm -rf /usr/bin/mysql
    ln -s ${basedir}/bin/mysql /usr/bin/mysql
}

function init() {
    ################初始化######################
    # 创建目录或者取清除 mysql data 目录
    if [ -d ${datadir} ]; then
        rm -rf ${datadir}
    else
        mkdir -p ${datadir}
    fi
    #创建 mysql data目录子目录
    mkdir -p {${datadir}/data,${mysqltmp},${logdir},${elogdir},${blogdir}}
    touch ${elogdir}/mysql.err

    ########创建用户,mysql目录授权########
    # 添加用户、用户组
    groupadd ${user}
    useradd -r -g ${user} ${user}
    # 目录授权
    chown -R ${user}:${user} ${basedir}
    chown -R ${user}:${user} ${datadir}

    # 执行初始化命令
    ## 参数 --initialize-insecure空密码
    echo "[${longtime}] initialize mysql"
    ${basedir}/bin/mysqld --defaults-file=tmp/my.cnf.tmp --user=${user} --initialize-insecure
    # 修改权限
    chown -R ${user}:${user} ${datadir}
    # 启动mysql
    echo "[${longtime}] start mysql"
    ${basedir}/bin/mysqld&

    while [ ! -f ${pidfile} ]
    do
        echo "wait mysqld start...pidfile:${pidfile}"
        sleep 1
    done
    sleep 1
    echo "[${longtime}] start mysqld server success"
}

function set_access_passwd() {
    # 设置本地访问密码
    echo "[${longtime}] set locacl password "
    ${basedir}/bin/mysql -uroot -e "alter user 'root'@'localhost' identified by '123456';FLUSH PRIVILEGES;"
    if [ $? -ne 0 ]; then
        echo -e "\033[31m exec mysql failed: so exit insert\033[0m"
        exit 1
    fi

    echo "[${longtime}] set remote access : '${loginuser}'@'%' "

    ## 读取初始化变量, 这里再次读取变量，可以让改函数单独使用
    source init_variable
    # 检查变量,写入默认值
    source check_var
    checkLoginVar
    mysql -p123456 -e "create user '${loginuser}'@'%' identified  with mysql_native_password by '${password}';GRANT ALL PRIVILEGES ON *.* to '${loginuser}'@'%';FLUSH PRIVILEGES;"
    # 设置完需关闭mysql, 不然设置开机启动时无法进行关闭.
    ${basedir}/bin/mysqladmin -p123456 shutdown
    echo "[${longtime}] seting  end"
}


function full_install() {
    generateConfig
    deploy
    init
}

function re_init() {
    ##########重新初始化###########
    # mysql 已安装部署完成的情况下可以重复进行初始化,免去安装部署步骤
    generateConfig
    init
}